#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlError>
#include <QDebug>
#include "employee.h"
#include "address.h"

// 注册QSet元类型
Q_DECLARE_METATYPE(QSet<QObject*>)

bool initDatabase() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("test.db");
    if (!db.open()) {
        qDebug() << "Cannot open database:" << db.lastError().text();
        return false;
    }
    return true;
}

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 注册元类型
    qRegisterMetaType<QSet<QObject*>>("QSet<QObject*>");
    
    if (!initDatabase())
        return 1;

    // 创建并保存一个Employee对象
    Employee* employee = new Employee;
    employee->setName("John Doe");
    employee->setAge(30);
    
    // 添加地址
    Address* addr1 = new Address(employee);
    addr1->setStreet("123 Main St");
    addr1->setCity("New York");
    addr1->setCountry("USA");
    employee->addAddress(addr1);
    
    Address* addr2 = new Address(employee);
    addr2->setStreet("456 Elm St");
    addr2->setCity("Los Angeles");
    addr2->setCountry("USA");
    employee->addAddress(addr2);

    if (employee->save()) {
        qDebug() << "Employee saved with ID:" << employee->id();
        
        // 从数据库加载对象
        Employee* loadedEmployee = new Employee;
        if (loadedEmployee->load(employee->id())) {
            qDebug() << "Loaded employee:" << loadedEmployee->name() << loadedEmployee->age();
            qDebug() << "Addresses:" << loadedEmployee->addresses().size();
            
            foreach (Address* addr, loadedEmployee->addresses()) {
                qDebug() << "  -" << addr->street() << addr->city() << addr->country();
            }
        }
        delete loadedEmployee;
    }

    delete employee;
    return 0;
}

#include "employee.moc"
#include "address.moc"    